import math
import threading
from main_thread.info_init import shiplist
import time
import sympy
class UAV():
    def __init__(self, x, y):
        """
        无人机初始函数
        :param x: 横坐标
        :param y: 纵坐标
        """
        self.x = x
        self.y = y
        self.speed = 120
        self.orderlist = []
        for each_ship in shiplist:
            this_time = each_ship.res + self.chase_time(each_ship)
            self.orderlist.append(this_time)

    def chase_time(self, ship):
        """
        追逐商船的时间
        :param ship:
        :return: time
        """
        t = sympy.symbols("t")
        ti = sympy.solve((ship.y - t * ship.speed * ship.ssin - self.y) ** 2 + (
                    ship.x - t * ship.speed * ship.ccos - self.x) ** 2 - 14400 * t * t, t)
        for i in ti:
            if i < 0:
                ti.remove(i)
        return min(ti)

    def choose_task(self):

        """
        从商船列表中选择优先级最高的商船
        :param shiplist:
        :return: ship
        """
        self.orderlist = []
        for each_ship in shiplist:
            this_time = 0.2 * each_ship.res + 0.8 * self.chase_time(each_ship)
            self.orderlist.append(this_time)

        task_index = self.orderlist.index(min(self.orderlist))
        task_ship = shiplist[task_index]

        mutex = threading.Lock()
        mutex.acquire()
        shiplist.remove(task_ship)

        mutex.release()
        print(threading.currentThread().name + " " + str(task_ship.index))
        time.sleep(0.1*(1/6 + self.chase_time(task_ship)))
        with open('thread-3.txt', 'a') as f:
            f.write(threading.currentThread().name + " " + str(task_ship.index)+'\n')
        f.close()
        return task_ship


    def finish_deteck(self, task_ship):
        finish_time = 1/6 + self.chase_time(task_ship)
        # self.x = task_ship.x
        # self.y = task_ship.y

        for each_ship in shiplist:
            mutex = threading.Lock()
            mutex.acquire()
            each_ship.x -= each_ship.speed * finish_time * (each_ship.x/(math.sqrt(math.pow(each_ship.x, 2) + math.pow(each_ship.y,2))))
            each_ship.y -= each_ship.speed * finish_time * (each_ship.y/(math.sqrt(math.pow(each_ship.x, 2) + math.pow(each_ship.y, 2))))
            each_ship.res -= finish_time
            mutex.release()
        self.x = task_ship.x
        self.y = task_ship.y
        for each_ship in shiplist:
            if each_ship.res < 0:
                print(str(each_ship.index) + 'th boat has pass across the line')
                exit(0)
